<template>
  <div>
    <Section class="bg-base-300">
      <div class="grid grid-cols-12 gap-y-10 pt-6 sm:pt-10 md:gap-x-10">
        <!-- Featured image -->
        <div class="col-span-12 lg:col-span-5">
          <img
            class="mx-auto block w-full max-w-full rounded-2xl object-cover md:h-[447px]"
            width="1200"
            height="800"
            :src="post?.cover"
            :alt="post?.title"
          />
        </div>

        <div class="col-span-12 lg:col-span-5 lg:col-start-7">
          <div class="flex h-full items-center">
            <div class="w-full">
              <!-- Categories -->
              <div class="mb-4">
                <div class="flex flex-row flex-wrap items-start gap-2">
                  <RouterLink
                    v-for="tag in post?.tags"
                    :key="tag.id"
                    :to="{ name: 'tag-details', params: { id: tag.id } }"
                    class="inline-block rounded-full bg-primary px-3 py-1 font-sans text-xs text-white shadow-lg shadow-primary/20"
                  >
                    {{ tag.name }}
                  </RouterLink>
                </div>
              </div>
              <!-- Title -->
              <h1 class="mt-8 font-sans text-3xl font-bold">
                {{ post?.title }}
              </h1>
              <p class="my-4 font-sans text-sm text-base-content/60">
                {{ post?.digest }}
              </p>
              <div class="flex items-center justify-between">
                <div class="flex items-center gap-4">
                  <RouterLink
                    :to="{
                      name: 'author-details',
                      params: { id: post?.authorId },
                    }"
                  >
                    <img
                      :src="post?.avatar ?? `/api/avatar/${post?.nickname}.svg`"
                      :alt="post?.nickname"
                      class="h-10 w-10 rounded-full sm:h-12 sm:w-12"
                    />
                  </RouterLink>
                  <div class="font-sans text-sm">
                    <RouterLink
                      :to="{
                        name: 'author-details',
                        params: { id: post?.authorId },
                      }"
                      class="text-xl font-medium leading-none transition duration-500 ease-in-out hover:text-info/60"
                    >
                      {{ post?.nickname }}
                    </RouterLink>
                    <p class="my-2 text-xs text-base-content/60">
                      发布于：{{ post?.updatedAt }}
                    </p>
                  </div>
                </div>
                <div class="font-sans text-xs text-base-content/60 sm:text-sm">
                  <span class="pr-2">阅读量：</span>
                  <span>{{ post?.hits }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </Section>
    <Section class="pb-8">
      <ZMdView
        class="xxl:max-w-3xl xxl:prose-lg prose prose-purple mx-auto max-w-2xl dark:prose-invert"
        :content="post?.content"
        html
        xhtml-out
      />
    </Section>
    <Section class="bg-base-200">
      <SectionTitle
        title="评论"
        description="以下是本站其他作者留下的评论，让我们一起讨论对文章的看法。"
      />
      <ZForm
        v-if="userStore.isLogin"
        :initial-values="initialValues"
        :rules="rules"
        @success="onSuccess"
        #="{ cBinds, errors, resetForm }"
      >
        <ZFormItem label="评论内容" name="description" :errors="errors">
          <ZTextArea class="w-full" :rows="1" v-bind="cBinds.description" />
        </ZFormItem>
        <div class="flex justify-end gap-4 px-4">
          <ZButton class="btn-primary" :loading="isFetching">保存评论</ZButton>
          <ZButton type="reset" class="btn-accent" @click="resetForm">
            重置
          </ZButton>
        </div>
      </ZForm>
      <ul class="mb-4">
        <li
          class="my-2 flex items-center gap-4"
          v-for="comment in comments"
          :key="comment.id"
        >
          <div class="h-8 w-8">
            <img
              class="h-full w-full object-cover"
              :src="comment.avatar ?? `/api/avatar/${comment.nickname}.svg`"
              alt="avatar"
            />
          </div>
          <div>
            <h3 class="font-sans text-2xl font-medium">
              <RouterLink
                class="transition-colors duration-300 hover:text-primary"
                :to="{
                  name: 'author-details',
                  params: { id: comment.authorId },
                }"
              >
                {{ comment.nickname }}
              </RouterLink>
              <small class="mx-2 text-sm text-base-content/60">
                于{{ comment.createdAt }}评论到：
              </small>
            </h3>
            <p
              class="text-base-content/80 transition-colors duration-1000 hover:text-secondary"
            >
              {{ comment.description }}
            </p>
          </div>
        </li>
      </ul>
      <ZPagination
        :total="total"
        v-model:page="page"
        v-model:page-size="pageSize"
        :buttons="['first', 'last']"
      />
    </Section>
  </div>
</template>
<script setup lang="ts">
import ZMdView from "@/components/ZMdView.vue";
import { useApiFetch, ApiResponse } from "@/composables/useApiFetch";
import type { Post, User, Tag, Comment } from "@/stores/types";
import { useRouteParamsWith } from "@/composables/useRouteParamsWith";
import { usePageFetch } from "@/composables/usePageFetch";
import { z } from "zod";
import { SubmissionContext } from "vee-validate";
import { useUserStore } from "@/stores/user";

const blogId = useRouteParamsWith("id");
const url = computed(() => `/posts/${blogId.value}`);

const { data } = useApiFetch(url, { refetch: true }).json<
  ApiResponse<Post & User & { tags: Tag[] }>
>();
const post = computed(() => data.value?.object);
// 获取评论
type CommentWithAuthor = Comment & {
  nickname: string;
  avatar: string;
};
const {
  data: commentsData,
  total,
  page,
  pageSize,
} = usePageFetch<CommentWithAuthor>(
  computed(() => `/posts/${blogId.value}/comments/`),
  { pageSize: 12 },
);
const comments = ref<CommentWithAuthor[]>([]);
watch(commentsData, () => {
  if (commentsData.value?.success) {
    comments.value = commentsData.value?.query.results;
  }
});
// 添加评论
const userStore = useUserStore();
const rules = z.object({
  description: z.string().min(3, "评论内容不能少于3个字"),
});
const initialValues: z.infer<typeof rules> = {
  description: "",
};
const { isFetching, post: postComment } = useApiFetch("/user/comments", {
  immediate: false,
});
const onSuccess = async (values: any, { resetForm }: SubmissionContext) => {
  const res: Response = await postComment({
    ...values,
    postId: blogId.value,
  }).execute();
  const data: ApiResponse = await res.json();
  if (data.success) {
    // 添加评论
    comments.value.unshift(data.object);
    // 重置表单
    resetForm();
  }
};
</script>
